<template>
  <view class="container">
    <view class="header">
      <text class="title">{{ paperName }}</text>
      <text class="timer">{{ timeDisplay }}</text>
    </view>
    <uni-transition mode-class="fade" :show="!!currentQuestion">
      <uni-card v-if="currentQuestion" :is-shadow="true" margin="20px 0">
        <view class="progress">
          <text class="progress-text">第 {{ currentIndex + 1 }} 题 / 共 {{ questions.length }} 题</text>
          <view class="progress-bar"><view class="progress-fill" :style="{ width: progressPercent + '%' }"></view></view>
        </view>
        <view class="question-content"><text class="question-text">{{ currentQuestion.question }}</text></view>
        <view class="options-list">
          <view v-for="(option, idx) in currentQuestion.options" :key="idx" class="option-item" :class="{
            'selected': selectedAnswer === option.optionKey,
            'correct': showAnswer && option.optionKey === currentQuestion.answer,
            'wrong': showAnswer && selectedAnswer === option.optionKey && selectedAnswer !== currentQuestion.answer
          }" @click="selectOption(option.optionKey)">
            <text class="option-label">{{ option.optionKey }}.</text>
            <text class="option-text">{{ option.optionValue }}</text>
            <view v-if="showAnswer && option.optionKey === currentQuestion.answer" class="correct-mark">✓</view>
            <view v-if="showAnswer && selectedAnswer === option.optionKey && selectedAnswer !== currentQuestion.answer" class="wrong-mark">✗</view>
          </view>
        </view>
      </uni-card>
    </uni-transition>
    <view v-if="loading" class="loading"><text>加载中...</text></view>
    <view v-if="!loading && questions.length === 0" class="empty"><text>暂无题目</text></view>
    <view v-if="questions.length > 0" class="action-buttons">
      <button class="btn btn-default" :disabled="currentIndex === 0" @tap="prevQuestion">上一题</button>
      <button class="btn btn-primary" :disabled="currentIndex === questions.length - 1" @tap="nextQuestion">下一题</button>
      <button class="btn btn-primary" @tap="submitResult">交卷</button>
    </view>
    <uni-popup ref="resultPopup" type="center">
      <view class="result-popup">
        <text class="result-title">成绩报告</text>
        <text class="result-score">{{ correctCount }} / {{ questions.length }}</text>
        <text class="result-text">{{ resultText }}</text>
        <view class="result-actions">
          <button class="btn btn-primary" @tap="closeResult">完成</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { get, post } from '@/utils/api.js'

export default {
  data() {
    return {
      paperId: '',
      paperIndex: 1,
      paperName: '',
      questions: [],
      loading: false,
      currentIndex: 0,
      selectedAnswer: '',
      showAnswer: false,
      isCorrect: false,
      answers: [],
      correctCount: 0,
      timeLeft: 60 * 60,
      timer: null,
      resultText: ''
    }
  },
  computed: {
    currentQuestion() { return this.questions[this.currentIndex] || null },
    progressPercent() { if (!this.questions.length) return 0; return Math.round(((this.currentIndex + 1) / this.questions.length) * 100) },
    timeDisplay() {
      const m = Math.floor(this.timeLeft / 60)
      const s = this.timeLeft % 60
      const mm = m < 10 ? '0' + m : '' + m
      const ss = s < 10 ? '0' + s : '' + s
      return mm + ':' + ss
    }
  },
  onLoad(options) {
    this.paperIndex = parseInt(options.paperIndex || '1')
    this.paperId = options.paperId || ('paper-' + this.paperIndex)
    this.paperName = '试卷' + this.paperIndex
    this.init()
  },
  onUnload() {
    this.stopTimer()
    this.persistProgress()
  },
  methods: {
    async init() {
      this.loading = true
      let all = []
      try { const data = await get('/practice/questions'); all = Array.isArray(data) ? data : [] } catch(e) { try { all = uni.getStorageSync('cached_questions') || [] } catch(err) { all = [] } }
      const size = 100
      const start = (this.paperIndex - 1) * size
      const end = Math.min(start + size, all.length)
      this.questions = all.slice(start, end)
      try {
        const prog = uni.getStorageSync('exam_progress_' + this.paperId)
        if (prog && prog.currentIndex >= 0) {
          this.currentIndex = prog.currentIndex || 0
          this.answers = prog.answers || []
          this.timeLeft = prog.timeLeft > 0 ? prog.timeLeft : this.timeLeft
        }
      } catch(e) {}
      this.resetQuestion()
      this.startTimer()
      this.loading = false
    },
    selectOption(value) {
      if (!this.showAnswer && this.currentQuestion) {
        this.selectedAnswer = value
        const isCorrect = value === this.currentQuestion.answer
        this.isCorrect = isCorrect
        this.showAnswer = true
        const idx = this.answers.findIndex(a => a.id === this.currentQuestion.id)
        const record = { id: this.currentQuestion.id, userAnswer: value, isCorrect }
        if (idx >= 0) { this.answers.splice(idx, 1, record) } else { this.answers.push(record) }
        this.persistProgress()
        post('/practice/record', { questionId: this.currentQuestion.id, interviewQuestionId: this.currentQuestion.interviewQuestionId, userAnswer: value, isCorrect }).catch(() => {})
      }
    },
    prevQuestion() { if (this.currentIndex > 0) { this.currentIndex--; this.resetQuestion(); this.persistProgress() } },
    nextQuestion() { if (this.currentIndex < this.questions.length - 1) { this.currentIndex++; this.resetQuestion(); this.persistProgress() } },
    startTimer() {
      if (this.timer) return
      this.timer = setInterval(() => {
        if (this.timeLeft > 0) { this.timeLeft--; this.persistProgress() } else { this.autoSubmit() }
      }, 1000)
    },
    stopTimer() { if (this.timer) { clearInterval(this.timer); this.timer = null } },
    autoSubmit() { this.stopTimer(); this.submitResult(true) },
    submitResult(auto = false) {
      this.correctCount = this.answers.filter(a => a.isCorrect).length
      const score = this.correctCount
      let text = ''
      if (score >= 90) text = '优秀'
      else if (score >= 70) text = '良好'
      else if (score >= 60) text = '及格'
      else text = '继续努力'
      this.resultText = text
      try { uni.setStorageSync('paper_result_' + this.paperId, { score, total: this.questions.length, completed: true, time: Date.now() }) } catch(e) {}
      try { uni.removeStorageSync('exam_progress_' + this.paperId) } catch(e) {}
      this.$refs.resultPopup.open()
    },
    closeResult() { this.$refs.resultPopup.close(); uni.navigateBack() },
    resetQuestion() { this.selectedAnswer = ''; this.showAnswer = false; this.isCorrect = false },
    persistProgress() {
      try {
        uni.setStorageSync('exam_progress_' + this.paperId, { currentIndex: this.currentIndex, answers: this.answers, timeLeft: this.timeLeft })
      } catch(e) {}
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/theme.scss';
.container { min-height: 100vh; background-color: #F9FAFB; padding-bottom: 100px; }
.header { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; }
.title { font-size: 16px; color: #333; font-weight: 600; }
.timer { font-size: 16px; color: #FF7F50; font-weight: 600; }
.progress { padding: 10px 0; border-bottom: 1px solid #eee; margin-bottom: 20px; }
.progress-text { font-size: 14px; color: #333; }
.question-content { margin-bottom: 20px; }
.question-text { font-size: 16px; line-height: 1.6; color: #333; }
.options-list { margin-top: 20px; }
.option-item { display: flex; align-items: flex-start; padding: 12px; margin-bottom: 10px; border: 1px solid #e0e0e0; border-radius: 8px; background-color: #fff; position: relative; transition: all 0.3s; }
.option-item.selected { border-color: #FF7F50; background-color: #fff3ee; }
.option-item.correct { border-color: #4cd964; background-color: #f0fff4; }
.option-item.wrong { border-color: #ff3b30; background-color: #fff5f5; }
.option-label { font-weight: bold; margin-right: 8px; color: #333; }
.option-text { flex: 1; font-size: 15px; line-height: 1.5; color: #333; }
.correct-mark { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #4cd964; font-size: 20px; font-weight: bold; }
.wrong-mark { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #ff3b30; font-size: 20px; font-weight: bold; }
.loading, .empty { text-align: center; padding: 40px 20px; color: #999; }
.action-buttons { position: fixed; bottom: 0; left: 0; right: 0; display: flex; justify-content: space-around; padding: 15px; background-color: #fff; border-top: 1px solid #eee; box-shadow: 0 -2px 10px rgba(0,0,0,0.1); }
.action-buttons .btn { flex: 1; margin: 0 5px; padding: 12px 20px; border-radius: 8px; font-size: 16px; border: none; }
.result-popup { width: 600rpx; padding: 30rpx; background-color: #ffffff; border-radius: 24rpx; }
.result-title { font-size: 18px; color: #333; text-align: center; margin-bottom: 12px; }
.result-score { font-size: 24px; color: #FF7F50; text-align: center; font-weight: 600; margin-bottom: 12px; }
.result-text { text-align: center; font-size: 16px; color: #333; margin-bottom: 20px; }
.result-actions { display: flex; justify-content: center; }
.btn-primary { }
.btn-default { }
</style>